package com.wcl.demo.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.wcl.demo.R;
import com.wcl.demo.ui.adapter.ChosePersonAdapter;
import com.wcl.demo.utils.ActivityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/12/4.
 */
public class GroupAddFriendActivity extends Activity implements View.OnClickListener {
    private ListView add_friend_lv;
    private ChosePersonAdapter mAdapter;
    private int checkNum; // 记录选中的条目数量
    private ArrayList<String> list = new ArrayList<String>();
    private List<String> memberlist = new ArrayList<String>();
    private List<String> usernames;
    private String groupid;
    private String owner;
    private List<String> order_members;
    private ImageButton groupadd_back;
    private Button groupadd_add;
    private String add;
    private TextView group_chatTitle;


    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            Log.i("lanou555", "进来没?");
            //根据群聊ID从服务器获取群聊基本信息
            EMGroupManager.getInstance().createOrUpdateLocalGroup(group);
            order_members = group.getMembers();
            if ("add".equals(add)) {
                for (String ordermember : order_members) {
                    if (usernames.contains(ordermember)) {
                        usernames.remove(ordermember);
                    }
                }

                Log.i("lanou555", list.toString());
                Log.i("lanou555", list.size() + "");
            } else {
                List<String> stringList=getIntersection(usernames, order_members);
                stringList.remove(owner);
                usernames.clear();
                usernames=stringList;
            }
            list = (ArrayList<String>) usernames;
            mAdapter = new ChosePersonAdapter(list, GroupAddFriendActivity.this);
            add_friend_lv.setAdapter(mAdapter);

            /**
             * // 实例化自定义的MyAdapter
             mAdapter = new ChosePersonAdapter(list, this);
             // 绑定Adapter
             lv.setAdapter(mAdapter);
             */

            mAdapter.notifyDataSetChanged();

            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_add_friend);
        // 绑定Adapter

        Bundle bundle = ActivityUtils.fromSrc(this);
        this.groupid = bundle.getString("groupid");
        this.owner = bundle.getString("owner");
        this.add = bundle.getString("add");

        initView();
        if(!("add".equals(add))){
            group_chatTitle.setText("删除群成员");
        }
        initData();

        // 绑定listView的监听器
        add_friend_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // 取得ViewHolder对象，这样就省去了通过层层的findViewById去实例化我们需要的cb实例的步骤
                ChosePersonAdapter.ViewHolder holder = (ChosePersonAdapter.ViewHolder) arg1.getTag();
                // 改变CheckBox的状态
                holder.cb.toggle();
                // 将CheckBox的选中状况记录下来
                ChosePersonAdapter.getIsSelected().put(arg2, holder.cb.isChecked());
                // 调整选定条目
                if (holder.cb.isChecked() == true) {
                    checkNum++;
                } else {
                    checkNum--;
                }
//                // 用TextView显示
//                add_friend_tv.setText("已选中" + checkNum + "项");
            }
        });
        //------------------

    }

    EMGroup group;

    private void initData() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //   List<EMGroup> grouplist = EMGroupManager.getInstance().getGroupsFromServer();//需异步处理
                    group = EMGroupManager.getInstance().getGroupFromServer(groupid);
                    handler.sendEmptyMessage(200);

                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void initView() {

        try {
            usernames = EMChatManager.getInstance().getContactUserNames();
            Log.i("shaco", usernames.toString() + "<<<<<<<<<----------");
        } catch (EaseMobException e) {
            e.printStackTrace();
        }
        add_friend_lv = (ListView) findViewById(R.id.add_friend_lv);
        groupadd_back = (ImageButton) findViewById(R.id.groupadd_back);
        groupadd_add = (Button) findViewById(R.id.groupadd_add);
        groupadd_add.setOnClickListener(this);
        groupadd_back.setOnClickListener(this);
        group_chatTitle= (TextView) findViewById(R.id.group_chatTitle);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.groupadd_back:
                finish();
                break;
            case R.id.groupadd_add:
                if ("add".equals(add)) {
                    //群主加人调用此方法
                    try {
                        searchSelect();
                        if (owner.equals(EMChatManager.getInstance().getCurrentUser())) {
                            EMGroupManager.getInstance().addUsersToGroup(groupid, members);//需异步处理
                        } else {
                            //私有群里，如果开放了群成员邀请，群成员邀请调用下面方法
                            EMGroupManager.getInstance().inviteUser(groupid, members, null);//需异步处理
                        }
                    } catch (EaseMobException e) {
                        e.printStackTrace();
                    }
                } else {
                    //把username从群聊里删除
                    searchSelect();
                    for (int i = 0; i < members.length; i++) {
                        try {
                            EMGroupManager.getInstance().removeUserFromGroup(groupid, members[i]);//需异步处理
                        } catch (EaseMobException e) {
                            e.printStackTrace();
                        }
                    }
                }
                finish();

                break;
        }
    }

    int count = -1;

    String[] members;

    private void searchSelect() {
        List<String> newList = null;
        for (int i = 0; i < list.size(); i++) {
            if (ChosePersonAdapter.getIsSelected().get(i)) {
                count++;
                memberlist.add(list.get(i));

            }
        }
        members = new String[memberlist.size()];
        for (int i = 0; i < members.length; i++) {
            members[i] = memberlist.get(i);
            Log.i("haha", members[i] + "****");
        }
    }

    public static List<String> getIntersection(List<String> list1,
                                                List<String> list2) {
        List<String> result = new ArrayList<String>();
        for (String integer : list2) {//遍历list1
            if (list1.contains(integer)) {//如果存在这个数
                result.add(integer);//放进一个list里面，这个list就是交集
            }
        }
        return result;
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }
}
